using UnityEngine;

namespace Game.Networking.Server {
	public abstract class UnitEventsWatcher {

		public ComputingUnit Target => _target;

		protected ComputingUnit _target;

		public void Setup(ComputingUnit targetUnit) {
			if (targetUnit == null) {
				Debug.LogError($"UnitEventsWatcher.Setup: Attempt to attach wather to a null unit");
				return;
			}
			_target = targetUnit;
			targetUnit.OnAttachedEntityIdChanged.Subscribe(this, OnAttachedEntityIdChanged);
			targetUnit.OnStateChanged.Subscribe(this, OnUnitStateChanged);
			targetUnit.OnFileListChanged.Subscribe(this, OnFileListChanged);
			targetUnit.OnCodeFileUpdated.Subscribe(this, OnCodeFileUpdated);
			targetUnit.TextTerminal.OnTerminalCommand.Subscribe(this, OnTerminalCommand);
		}

		public void DeInit() {
			if ( _target == null ) {
				return;
			}
			_target.OnAttachedEntityIdChanged.Unsubscribe(OnAttachedEntityIdChanged);
			_target.OnFileListChanged.Unsubscribe(OnFileListChanged);
			_target.OnCodeFileUpdated.Unsubscribe(OnCodeFileUpdated);
			_target.OnStateChanged.Unsubscribe(OnUnitStateChanged);
			_target.TextTerminal?.OnTerminalCommand.Unsubscribe(OnTerminalCommand);
			_target = null;
		}

		/// <summary>
		/// Вызвать событие вручную, вместо триггера по EventBus
		/// Полезно для первоначальной инициализации
		/// </summary>
		/// <param name="newEntity"></param>
		public abstract void OnAttachedEntityIdChanged(uint newEntity);

		protected abstract void OnUnitStateChanged();

		protected abstract void OnFileListChanged();

		protected abstract void OnCodeFileUpdated(string fileName);

		protected abstract void OnTerminalCommand(TerminalCommandEvent cmd);
	}
}

